import 'dart:async';
import 'dart:isolate';
import 'dart:ui';

import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:permission_handler/permission_handler.dart';

import '../app_logger.dart';

// 前台服务命令
enum ForegroundServiceCommand {
  startRecording,
  stopRecording,
  updateStatus,
  initializeTranslation,
  enableBackgroundRecording, // 新增：启用后台录音功能
}

// 数据传输用的端口名
const String _kPortName = 'foreground_recorder_port';

// 前台服务处理器
@pragma('vm:entry-point')
void startForegroundService() {
  // 初始化Flutter前台任务处理器
  FlutterForegroundTask.setTaskHandler(ForegroundServiceHandler());
}

// 前台服务处理器
class ForegroundServiceHandler extends TaskHandler {
  // 通信端口
  SendPort? _sendPort;
  
  // 服务启动时调用
  @override
  Future<void> onStart(DateTime timestamp, TaskStarter starter) async {
    log.d('🎯 前台服务: 启动');

    // 注册端口用于与主应用通信
    final receivePort = ReceivePort();
    IsolateNameServer.registerPortWithName(receivePort.sendPort, _kPortName);
    
    // 监听来自主应用的消息
    receivePort.listen((dynamic data) {
      if (data is Map<String, dynamic>) {
        _handleMainAppMessage(data);
      }
    });

    // 更新通知为初始状态
    await FlutterForegroundTask.updateService(
      notificationTitle: '录音翻译助手',
      notificationText: '后台运行中，可随时开始录音翻译',
      notificationButtons: [
        const NotificationButton(id: 'start_recording', text: '开始录音'),
        const NotificationButton(id: 'open_app', text: '打开应用'),
      ],
    );
  }

  /// 处理来自主应用的消息
  void _handleMainAppMessage(Map<String, dynamic> data) {
    final type = data['type'] as String?;
    log.d('🎯 前台服务收到消息: $type');
    
    switch (type) {
      case 'translation_result':
        final text = data['text'] as String?;
        if (text != null) {
          _updateNotificationWithResult(text);
        }
        break;
      case 'asr_result':
        final text = data['text'] as String?;
        if (text != null) {
          _updateNotificationWithASR(text);
        }
        break;
      case 'connection_status':
        final isConnected = data['connected'] as bool? ?? false;
        _updateConnectionStatus(isConnected);
        break;
    }
  }

  /// 更新通知显示翻译结果
  void _updateNotificationWithResult(String translationText) {
    FlutterForegroundTask.updateService(
      notificationTitle: '翻译完成',
      notificationText: translationText.length > 50 
          ? '${translationText.substring(0, 50)}...'
          : translationText,
      notificationButtons: [
        const NotificationButton(id: 'open_app', text: '查看完整结果'),
      ],
    );
  }

  /// 更新通知显示ASR结果
  void _updateNotificationWithASR(String asrText) {
    FlutterForegroundTask.updateService(
      notificationTitle: '正在识别语音',
      notificationText: asrText.length > 50 
          ? '${asrText.substring(0, 50)}...'
          : asrText,
      notificationButtons: [
        const NotificationButton(id: 'open_app', text: '打开应用'),
      ],
    );
  }

  /// 更新连接状态
  void _updateConnectionStatus(bool isConnected) {
    if (isConnected) {
      FlutterForegroundTask.updateService(
        notificationTitle: '录音助手',
        notificationText: '已连接服务器，可以后台录音',
        notificationButtons: [
          const NotificationButton(id: 'open_app', text: '打开应用'),
        ],
      );
    } else {
      FlutterForegroundTask.updateService(
        notificationTitle: '录音助手',
        notificationText: '连接断开，正在重连...',
        notificationButtons: [
          const NotificationButton(id: 'open_app', text: '打开应用'),
        ],
      );
    }
  }

  @override
  void onRepeatEvent(DateTime timestamp) {
    // 定期检查和维护前台服务状态
    // 主要用于保持前台服务活跃
  }

  @override
  void onReceiveData(dynamic data) {
    if (data != null && data is Map<String, dynamic>) {
      final command = data['command'] as String?;

      if (command == ForegroundServiceCommand.startRecording.toString()) {
        _handleStartRecording(data);
      } else if (command == ForegroundServiceCommand.stopRecording.toString()) {
        _handleStopRecording();
      } else if (command == ForegroundServiceCommand.initializeTranslation.toString()) {
        _handleInitializeTranslation(data);
      } else if (command == ForegroundServiceCommand.updateStatus.toString()) {
        _handleUpdateStatus(data);
      } else if (command == ForegroundServiceCommand.enableBackgroundRecording.toString()) {
        _handleEnableBackgroundRecording(data);
      }
    }
  }

  /// 处理开始录音命令
  void _handleStartRecording(Map<String, dynamic> data) {
    log.d('🎯 前台服务: 开始录音');
    
    final fromLanguage = data['fromLanguage'] as String? ?? 'zh-CN';
    final toLanguage = data['toLanguage'] as String? ?? 'en-US';
    
    // 更新通知显示正在录音
    FlutterForegroundTask.updateService(
      notificationTitle: '正在录音',
      notificationText: '后台录音中，$fromLanguage → $toLanguage',
      notificationButtons: [
        const NotificationButton(id: 'stop_recording', text: '停止录音'),
        const NotificationButton(id: 'open_app', text: '打开应用'),
      ],
    );
  }

  /// 处理停止录音命令
  void _handleStopRecording() {
    log.d('🎯 前台服务: 停止录音');
    
    // 更新通知回到待机状态，但仍然可以开始录音
    FlutterForegroundTask.updateService(
      notificationTitle: '录音翻译助手',
      notificationText: '后台运行中，可随时开始录音翻译',
      notificationButtons: [
        const NotificationButton(id: 'start_recording', text: '开始录音'),
        const NotificationButton(id: 'open_app', text: '打开应用'),
      ],
    );
  }

  /// 处理启用后台录音功能
  void _handleEnableBackgroundRecording(Map<String, dynamic> data) {
    log.d('🎯 前台服务: 启用后台录音功能');
    
    final isConnected = data['isConnected'] as bool? ?? false;
    
    // 更新通知显示后台录音可用状态
    if (isConnected) {
      FlutterForegroundTask.updateService(
        notificationTitle: '录音翻译助手',
        notificationText: '后台运行中，可随时开始录音翻译',
        notificationButtons: [
          const NotificationButton(id: 'start_recording', text: '开始录音'),
          const NotificationButton(id: 'open_app', text: '打开应用'),
        ],
      );
    } else {
      FlutterForegroundTask.updateService(
        notificationTitle: '录音翻译助手',
        notificationText: '服务连接中，请稍后再试录音',
        notificationButtons: [
          const NotificationButton(id: 'open_app', text: '打开应用'),
        ],
      );
    }
  }

  /// 处理初始化翻译服务命令
  void _handleInitializeTranslation(Map<String, dynamic> data) {
    log.d('🎯 前台服务: 初始化翻译服务');
    
    // 这里可以初始化翻译服务连接
    // 由于前台服务在独立的isolate中运行，实际的WebSocket连接应该在主应用中维护
    // 前台服务主要负责录音和通知更新
  }

  /// 处理状态更新命令
  void _handleUpdateStatus(Map<String, dynamic> data) {
    final status = data['status'] as String?;
    final message = data['message'] as String? ?? '应用正在后台运行中';

    log.d('🎯 前台服务: 更新状态 - $status, $message');

    // 更新通知状态
    FlutterForegroundTask.updateService(
      notificationTitle: status ?? '录音助手',
      notificationText: message,
      notificationButtons: [
        const NotificationButton(id: 'open_app', text: '打开应用'),
      ],
    );
  }

  // 服务销毁时调用
  @override
  Future<void> onDestroy(DateTime timestamp, bool isAppKilled) async {
    log.d('🎯 前台服务: 销毁');
    
    // 注销端口
    IsolateNameServer.removePortNameMapping(_kPortName);
  }

  // 通知按钮点击事件
  @override
  void onNotificationButtonPressed(String id) {
    log.d('🎯 前台服务: 按钮点击 - $id');
    
    if (id == 'open_app') {
      // 启动应用
      FlutterForegroundTask.launchApp();
    } else if (id == 'stop_recording') {
      // 停止录音
      _handleStopRecording();
      // 通知主应用停止录音
      _sendMessageToMainApp({
        'type': 'stop_recording_request',
      });
    } else if (id == 'start_recording') {
      // 从通知启动录音
      log.d('🎯 从通知启动录音');
      // 通知主应用启动录音
      _sendMessageToMainApp({
        'type': 'start_recording_request',
      });
      
      // 更新通知状态为正在启动
      FlutterForegroundTask.updateService(
        notificationTitle: '正在启动录音',
        notificationText: '请稍等，正在初始化录音服务...',
        notificationButtons: [
          const NotificationButton(id: 'open_app', text: '打开应用'),
        ],
      );
    }
  }

  /// 发送消息给主应用
  void _sendMessageToMainApp(Map<String, dynamic> message) {
    // 这里需要实现与主应用的通信
    // 由于前台服务运行在独立的isolate中，需要通过端口通信
    try {
      _sendPort?.send(message);
    } catch (e) {
      log.d('🎯 发送消息到主应用失败: $e');
    }
  }

  // onRepeatEvent 已被移除，因为命令通过 onEvent 处理
}

// 前台服务管理类
class ForegroundRecorderService {
  // 单例模式
  static final ForegroundRecorderService _instance = ForegroundRecorderService._internal();
  factory ForegroundRecorderService() => _instance;
  ForegroundRecorderService._internal();

  // 服务状态
  bool _isRunning = false;
  bool get isRunning => _isRunning;
  
  // 与前台服务通信的端口
  SendPort? _foregroundSendPort;
  ReceivePort? _mainReceivePort;

  // 初始化服务
  void init() {
    // 初始化前台任务
    FlutterForegroundTask.init(
      androidNotificationOptions: AndroidNotificationOptions(
        channelId: 'foreground_recorder_service',
        channelName: '录音翻译服务',
        channelDescription: '用于后台录音和实时翻译的前台服务',
        channelImportance: NotificationChannelImportance.LOW,
        priority: NotificationPriority.MIN,
      ),
      iosNotificationOptions: const IOSNotificationOptions(
        showNotification: true,
        playSound: false,
      ),
      foregroundTaskOptions: ForegroundTaskOptions(
        eventAction: ForegroundTaskEventAction.nothing(),
        autoRunOnBoot: false,
        allowWakeLock: true,
        allowWifiLock: true,
      ),
    );
  }

  // 请求权限
  Future<bool> _requestPermissions() async {
    // 检查通知权限
    final NotificationPermission notificationPermission =
        await FlutterForegroundTask.checkNotificationPermission();
    if (notificationPermission != NotificationPermission.granted) {
      final requestedPermission = await FlutterForegroundTask.requestNotificationPermission();
      if (requestedPermission != NotificationPermission.granted) {
        log.d('🎯 前台服务: 通知权限未授予');
        return false;
      }
    }

    // 检查录音权限
    final microphoneStatus = await Permission.microphone.status;
    if (!microphoneStatus.isGranted) {
      final requestResult = await Permission.microphone.request();
      if (!requestResult.isGranted) {
        log.d('🎯 前台服务: 录音权限未授予');
        return false;
      }
    }

    return true;
  }

  // 启动前台服务
  Future<bool> start() async {
    if (_isRunning) return true;

    // 请求必要权限
    final hasPermissions = await _requestPermissions();
    if (!hasPermissions) {
      log.d('🎯 前台服务: 启动所需权限不足');
      return false;
    }

    try {
      // 设置与前台服务的通信
      _setupCommunication();
      
      // 启动前台服务
      final result = await FlutterForegroundTask.startService(
        notificationTitle: '录音翻译助手',
        notificationText: '准备就绪，可以后台录音翻译',
        callback: startForegroundService,
      );

      if (result is ServiceRequestSuccess) {
        _isRunning = true;
        log.d('🎯 前台服务启动成功');
        return true;
      } else if (result is ServiceRequestFailure) {
        log.d('🎯 启动前台服务失败: ${result.error}');
        _isRunning = false;
        return false;
      }
      _isRunning = false;
      return false;
    } catch (e) {
      log.d('🎯 启动前台服务异常: $e');
      _isRunning = false;
      return false;
    }
  }

  /// 设置与前台服务的通信
  void _setupCommunication() {
    // 查找前台服务的发送端口
    _foregroundSendPort = IsolateNameServer.lookupPortByName(_kPortName);
    
    // 创建接收端口监听前台服务的消息
    _mainReceivePort = ReceivePort();
    _mainReceivePort!.listen((dynamic data) {
      if (data is Map<String, dynamic>) {
        _handleForegroundServiceMessage(data);
      }
    });
  }

  /// 处理来自前台服务的消息
  void _handleForegroundServiceMessage(Map<String, dynamic> data) {
    final type = data['type'] as String?;
    log.d('🎯 主应用收到前台服务消息: $type');
    
    switch (type) {
      case 'stop_recording_request':
        // 前台服务请求停止录音
        // 这个回调会传递给UI层处理
        _onForegroundServiceAction?.call('stop_recording');
        break;
      case 'start_recording_request':
        // 前台服务请求启动录音
        // 这个回调会传递给UI层处理
        _onForegroundServiceAction?.call('start_recording');
        break;
    }
  }

  // 前台服务动作回调
  Function(String action)? _onForegroundServiceAction;

  // 停止前台服务
  Future<bool> stop() async {
    if (!_isRunning) return true;

    try {
      // 清理通信端口
      _mainReceivePort?.close();
      _mainReceivePort = null;
      _foregroundSendPort = null;
      
      // 停止前台服务
      final result = await FlutterForegroundTask.stopService();

      if (result is ServiceRequestSuccess) {
        _isRunning = false;
        log.d('🎯 前台服务停止成功');
        return true;
      } else if (result is ServiceRequestFailure) {
        log.d('🎯 停止前台服务失败: ${result.error}');
        return false;
      }
      return false;
    } catch (e) {
      log.d('🎯 停止前台服务异常: $e');
      return false;
    }
  }

  // 通知前台服务开始录音
  void notifyStartRecording({
    required String fromLanguage,
    required String toLanguage,
  }) {
    if (!_isRunning) {
      log.d('🎯 前台服务未运行，无法发送开始录音通知');
      return;
    }

    FlutterForegroundTask.sendDataToTask({
      'command': ForegroundServiceCommand.startRecording.toString(),
      'fromLanguage': fromLanguage,
      'toLanguage': toLanguage,
    });
  }

  // 通知前台服务停止录音
  void notifyStopRecording() {
    if (!_isRunning) {
      log.d('🎯 前台服务未运行，无法发送停止录音通知');
      return;
    }

    FlutterForegroundTask.sendDataToTask({
      'command': ForegroundServiceCommand.stopRecording.toString(),
    });
  }

  // 发送翻译结果到前台服务
  void sendTranslationResult(String translationText) {
    if (!_isRunning) return;
    
    _foregroundSendPort?.send({
      'type': 'translation_result',
      'text': translationText,
    });
  }

  // 发送ASR结果到前台服务
  void sendASRResult(String asrText) {
    if (!_isRunning) return;
    
    _foregroundSendPort?.send({
      'type': 'asr_result',
      'text': asrText,
    });
  }

  // 发送连接状态到前台服务
  void sendConnectionStatus(bool isConnected) {
    if (!_isRunning) return;
    
    _foregroundSendPort?.send({
      'type': 'connection_status',
      'connected': isConnected,
    });
  }

  // 更新前台服务状态
  void updateStatus(String status, String message) {
    if (!_isRunning) {
      log.d('🎯 前台服务未运行，无法发送更新状态通知');
      return;
    }

    FlutterForegroundTask.sendDataToTask({
      'command': ForegroundServiceCommand.updateStatus.toString(),
      'status': status,
      'message': message,
    });
  }

  // 设置前台服务动作回调
  void setOnForegroundServiceAction(Function(String action) callback) {
    _onForegroundServiceAction = callback;
  }

  // 启用后台录音功能
  void enableBackgroundRecording({required bool isConnected}) {
    if (!_isRunning) {
      log.d('🎯 前台服务未运行，无法启用后台录音');
      return;
    }

    FlutterForegroundTask.sendDataToTask({
      'command': ForegroundServiceCommand.enableBackgroundRecording.toString(),
      'isConnected': isConnected,
    });
  }

  // 释放资源
  void dispose() {
    if (_isRunning) {
      stop();
    }
    _mainReceivePort?.close();
  }
}
